#!/bin/bash

## Generate bibtex key from citeulike id
## If multiple ids are given, create sed command string for auto-replacement
##
## Uses bibtool to format/normalize the bibtex and generate the bibtex key.

repo=/home/pepe/files/lispler/citeulike
bibtool_res=/home/pepe/files/lispler/git/configs/bibtex/bibtool_keys_marwin.rc

# if $1 is file, treat it as latex log and generate $ids from missing refs
if [ -f "$1" ]; then
  file="$1"
  for id in $(grep "Warning--I didn't find a database entry for" "$file"|sed s/"\"$"//|sed s/".*\""//); do
    
    test 0 -lt "$id" > /dev/null 2>&1 || continue;
    if [ -f $repo/$id/$id.bib ]; then
      ids="$ids $id"
    else
      echo "No such bibtex ID $id"
    fi
  done
else
# otherwise, just use user input
  ids="$*"
fi

# generate sed command for given IDs

for id in $ids; do
	file=$(ls $repo/$id/*|grep -v ^.priority$|grep -v .bib$)
	filename=$(basename "$file")
  echo -n "cp $file ./"
  echo -n "$(bibtool -r $bibtool_res $repo/$id/$id.bib|grep @|awk '{print $2}'|sed s/,//)"
  echo -n "_$filename"
	echo
done

echo 
